//
// Created by hkkzzxz on 24-9-4.
//

#include <json/value.h>
#include "SuperAdminService.h"
#include "Security.h"
#include "MySQLDatabaseModel.h"
#include "AdminInformation.h"

bool SuperAdminService::addAdmin(const std::string &id, const std::string &name, const std::string &password) {
    // 生成用户的盐值以及加密密码
    auto security = std::make_unique<Security>();
    std::string salt = security->generateSalt();
    std::string hashPassword = security->hashPassword(password, salt);

    // 写入MySQL数据库
    std::string insert = "INSERT INTO user (id, name, salt, password, identity) VALUES (?, ?, ?, ?, ?)";
    std::vector<std::string> params = {id, name, salt, hashPassword, "admin"};
    auto mysqlDatabaseModel = std::make_unique<MySQLDatabaseModel>();
    if (mysqlDatabaseModel->insert(insert, params)) {
        return true;
    }
    return false;
}

bool SuperAdminService::deleteAdmin(const std::string &id, const std::string &name) {
    // 从MySQL数据库中删除信息
    std::string update = "DELETE FROM user WHERE id = ? AND name = ?";
    std::vector<std::string> params = {id, name};
    auto mysqlDatabaseModel = std::make_unique<MySQLDatabaseModel>();
    if (mysqlDatabaseModel->update(update, params)) {
        return true;
    }
    return false;
}

std::string SuperAdminService::checkAdmin() {
    // 从MySQl数据库user表里面读取
    std::string query = "SELECT id, name FROM user WHERE identity = 'admin'";
    std::vector<std::string> params = {};
    auto mysqlDatabaseModel = std::make_unique<MySQLDatabaseModel>();
    auto result = mysqlDatabaseModel->queryModel<AdminInformation>(query, params);
    if (result.empty()) {
        return "";
    }

    Json::Value data;
    for (auto &i: result) {
        Json::Value temp;
        temp["id"] = i->getId();
        temp["name"] = i->getName();
        data.append(temp);
    }

    return data.toStyledString();
}
